package com.example.zhihuigongdi.utils;

import com.example.zhihuigongdi.commer.CommonException;
import com.example.zhihuigongdi.commer.common.enums.SecurityEnum;
import com.example.zhihuigongdi.entity.User;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class CheckUtil {
    //检测用户权限
    public Boolean checkUser(User user){
        if (user == null) {
            throw new CommonException("登录已过期，请重新登录");
        }
        return true;
    }

    @Autowired
    private RedisCache redisCache;
    //获取当前用户
    public  User getUser(){
        if (RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue());
            if (token==null || token.equals("null")){
                return null;
            }
            String userid;
            try {
                Claims claims
                        = JwtUtil.parseJWT(token);
                //获取存储在claims中的用户信息
                userid = claims.getSubject();

                String redisKey = "login:" + userid;
                //校验redis中是否有权限
                User user =redisCache.getCacheObject(redisKey);
                System.out.println(user);
                return user;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
        return null;
    }
}
